# @time     :2022/2/24
# @Author   :Simple
# @FileName :conftest
import time

import allure
import pytest

# from util.browser import init_browser_info
from allure_commons.types import AttachmentType
from selenium import webdriver

from util.driver import BaseDriver
from util.logger import log as logger


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    用例失败处截图并保存到报告中
    :param item:
    :return:
    """
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    if report.when == 'call' or report.when == 'setup':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            case_path = report.nodeid.replace("::", "-") + ".png"
            if '[' in case_path:
                logger.debug(case_path)
                logger.debug(case_path.split('-')[0])
                case_name = case_path.split('-')[0] + "].png"
            else:
                case_name = case_path
            try:
                screen_img = driver.get_screenshot_as_png()
                allure.attach(screen_img, name=case_name, attachment_type=AttachmentType.PNG)
            except Exception as e:
                logger.error(e)
        report.extra = extra


def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的item的name和nodeid的中文显示在控制台上
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")


# def pytest_addoption(parser):
#     parser.addoption("--cmdopt", action="store", default=None, help=None)
#     parser.addoption("--browser_opt", action="store", default=None, help=None)
#
#
# @pytest.fixture(scope="session")
# def cmdopt(request):
#     """
#     接收命令行传过来的值
#     """
#     return request.config.getoption("--cmdopt")
#
#
# @pytest.fixture(scope='session')
# def browser_opt(request):
#     """
#     接收命令行传过来的browser_opt值
#     :param request:
#     :return:
#     """
#     return request.config.getoption("--browser_opt")


@pytest.fixture(scope="session")
def common_driver():
    """
    启动浏览器、获取driver
    :param cmdopt:
    :param flag:
    :return:
    """
    global driver
    try:
        driver = BaseDriver.get_driver()
        yield driver
        driver.quit()
        time.sleep(2)
    finally:
        print("test end!")

